/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sita.friend.ui.adapter;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sita.bike.R;
import com.sita.bike.model.EaseUser2;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Account;
import com.sita.bike.rest.model.AddRequest;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.utils.AccountUtils;
import com.sita.friend.FriendHelper;
import com.sita.friend.db.InviteMessgeDao;
import com.sita.friend.domain.InviteMessage;
import com.sita.friend.domain.InviteMessage.InviteMesageStatus;
import com.sita.friend.utils.MessageUtils;

import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class NewFriendsMsgAdapter extends ArrayAdapter<InviteMessage> {

    private Context context;
    private InviteMessgeDao messgeDao;

    public NewFriendsMsgAdapter(Context context, int textViewResourceId, List<InviteMessage> objects) {
        super(context, textViewResourceId, objects);
        this.context = context;
        messgeDao = new InviteMessgeDao(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(context, R.layout.em_row_invite_msg, null);
            holder.avator = (ImageView) convertView.findViewById(R.id.avatar);
            holder.reason = (TextView) convertView.findViewById(R.id.message);
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.status = (Button) convertView.findViewById(R.id.user_state);
            holder.groupContainer = (LinearLayout) convertView.findViewById(R.id.ll_group);
            holder.groupname = (TextView) convertView.findViewById(R.id.tv_groupName);
            // holder.time = (TextView) convertView.findViewById(R.id.time);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        String str1 = context.getResources().getString(R.string.Has_agreed_to_your_friend_request);
        String str2 = context.getResources().getString(R.string.agree);

        String str3 = context.getResources().getString(R.string.Request_to_add_you_as_a_friend);
        String str4 = context.getResources().getString(R.string.Apply_to_the_group_of);
        String str5 = context.getResources().getString(R.string.Has_agreed_to);
        String str6 = context.getResources().getString(R.string.Has_refused_to);
        final InviteMessage msg = getItem(position);
        if (msg != null) {
            if (msg.getGroupId() != null) { // 显示群聊提示
                holder.groupContainer.setVisibility(View.VISIBLE);
                holder.groupname.setText(msg.getGroupName());
            } else {
                holder.groupContainer.setVisibility(View.GONE);
            }

            holder.reason.setText(msg.getReason());
            holder.name.setText(msg.getFrom());
            // holder.time.setText(DateUtils.getTimestampString(new
            // Date(msg.getTime())));
            if (msg.getStatus() == InviteMesageStatus.BEAGREED) {
                holder.status.setVisibility(View.INVISIBLE);
                holder.reason.setText(str1);
            } else if (msg.getStatus() == InviteMesageStatus.BEINVITEED || msg.getStatus() == InviteMesageStatus.BEAPPLYED) {
                holder.status.setVisibility(View.VISIBLE);
                holder.status.setEnabled(true);
//				holder.status.setBackgroundResource(android.R.drawable.btn_default);
                holder.status.setText(str2);
                if (msg.getStatus() == InviteMesageStatus.BEINVITEED) {
                    if (msg.getReason() == null) {
                        // 如果没写理由
                        holder.reason.setText(str3);
                    }
                } else { //入群申请
                    if (TextUtils.isEmpty(msg.getReason())) {
                        holder.reason.setText(str4 + msg.getGroupName());
                    }
                }
                // 设置点击事件
                holder.status.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 同意别人发的好友请求
                        acceptInvitation(holder.status, msg);
                    }
                });
            } else if (msg.getStatus() == InviteMesageStatus.AGREED) {
                holder.status.setText(str5);
                holder.status.setBackgroundDrawable(null);
                holder.status.setEnabled(false);
            } else if (msg.getStatus() == InviteMesageStatus.REFUSED) {
                holder.status.setText(str6);
                holder.status.setBackgroundDrawable(null);
                holder.status.setEnabled(false);
            }

            // 设置用户头像
        }

        return convertView;
    }

    /**
     * 同意好友请求或者群申请
     *
     * @param button
     * @param msg
     */
    private void acceptInvitation(final Button button, final InviteMessage msg) {
        final ProgressDialog progressDialog = new ProgressDialog(context);
        String str1 = context.getResources().getString(R.string.Are_agree_with);
        final String str2 = context.getResources().getString(R.string.Has_agreed_to);
        final String str3 = context.getResources().getString(R.string.Agree_with_failure);
        progressDialog.setMessage(str1);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        msg.setStatus(InviteMesageStatus.AGREED);

        final AddRequest addRequest = new AddRequest();
        addRequest.mAccountId = AccountUtils.getAccountID();
        addRequest.mContactId = msg.getAccountId();
        RestClient.getRestNormalService().accept(addRequest, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200 && restResponse.mErrorCode.equals("0")) {
                    button.setText(str2);
                    button.setTextColor(Color.BLACK);
                    button.setBackgroundDrawable(null);
                    button.setEnabled(false);

                    // 更新db
                    ContentValues values = new ContentValues();
                    values.put(InviteMessgeDao.COLUMN_NAME_STATUS, InviteMesageStatus.AGREED.ordinal()/*msg.getStatus().ordinal()*/);
                    messgeDao.updateMessage(msg.getId(), values);

                    // 添加好友db
                    AccountUtils.asyncFetchFriendInfo(addRequest.mContactId, new AccountUtils.AsyncFetchFriendInfoListener() {
                        @Override
                        public void success(Account account) {
                            AccountUtils.saveFriend(account);
                            String content = context.getResources().getString(R.string.friend_accepted_message);
                            String username = (TextUtils.isEmpty(account.mNickName) ? account.mMobile : account.mNickName);
                            MessageUtils.createTxtMessage(account.mAccountId, AccountUtils.getAccountID(), username + content, false);
                            // no need to post event
                        }

                        @Override
                        public void failed() {

                        }
                    });
                    FriendHelper.getInstance().saveContact(new EaseUser2(msg.getFrom()));
                    progressDialog.dismiss();


                } else {
                    Toast.makeText(context, str3 + restResponse.mData, Toast.LENGTH_LONG).show();
                    progressDialog.dismiss();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                // TODO: 2016/1/21
                Toast.makeText(context, str3 + error.getMessage(), Toast.LENGTH_LONG).show();
//                RetrofitUtils.displayError(NewFriendsMsgActivity.class, error);
                progressDialog.dismiss();
            }
        });

    }


    private static class ViewHolder {
        ImageView avator;
        TextView name;
        TextView reason;
        Button status;
        LinearLayout groupContainer;
        TextView groupname;
        // TextView time;
    }

}
